package com.zkthink.zhl.order.service.impl;


import cn.hutool.core.date.DatePattern;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.domain.AlipayTradeRefundApplyModel;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.binarywang.wxpay.bean.order.WxPayAppOrderResult;
import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.payments.jsapi.model.*;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;

import com.wechat.pay.java.service.payments.model.Transaction;
import com.zkthink.base.R;
import com.zkthink.base.service.SuperServiceImpl;
import com.zkthink.ceres.common.enums.AdjustStatuseEnum;
import com.zkthink.ceres.common.utils.QcodeUtil;
import com.zkthink.ceres.file.properties.FileServerProperties;
import com.zkthink.ceres.member.entity.Member;
import com.zkthink.ceres.member.service.MemberService;
import com.zkthink.ceres.order.dao.CommentMapper;
import com.zkthink.ceres.pay.service.PayService;
import com.zkthink.ceres.pay.wechat.v3.http.WechatPayHttpClientBuilder;
import com.zkthink.ceres.store.dao.StoreMapper;
import com.zkthink.ceres.store.dao.StoreWithdrawHisMapper;
import com.zkthink.ceres.store.dto.HeXiaoDto;
import com.zkthink.ceres.store.dto.StoreWithdrawHisSaveDTO;
import com.zkthink.ceres.store.entity.Store;
import com.zkthink.ceres.store.entity.StoreWithdrawHis;
import com.zkthink.ceres.store.service.StoreService;
import com.zkthink.ceres.store.vo.XiadanVo;
import com.zkthink.clh.order.dto.*;
import com.zkthink.clh.order.dto.ChlOrderPageDTO;
import com.zkthink.clh.order.entity.*;
import com.zkthink.clh.order.vo.*;
import com.zkthink.database.mybatis.conditions.Wraps;
import com.zkthink.exception.BizException;
import com.zkthink.utils.StrPool;
import com.zkthink.zhl.order.dao.*;
import com.zkthink.zhl.order.service.ChlCouponsService;
import com.zkthink.zhl.order.service.ChlOrderService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConfig;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.zkthink.utils.DateUtils.DEFAULT_MONTH_FORMAT_SLASH;

/**
 * <p>
 * 业务实现类
 * 车惠龙订单表
 * </p>
 *
 * @author chenke
 * @date 2022-04-24
 */
@Slf4j
@Service
public class ChlOrderServiceImpl extends SuperServiceImpl<ChlOrderMapper, ChlOrder> implements ChlOrderService {

    @Autowired
    private MemberService memberService;
    @Autowired
    private PayService payService;
    @Resource
    private FileServerProperties fileProperties;
    @Autowired
    private StoreService storeService;
    @Autowired
    private ChlConfigMapper chlConfigMapper;
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private ChlMemberTichengMapper chlMemberTichengMapper;
    @Autowired
    private ChlLbtMapper chlLbtMapper;
    //   @Autowired
//   private PayCallBackService payCallBackService;
//    @Autowired
//    private AppletProductMapper appletProductMapper;
    @Autowired
    private RedisConnectionFactory j2CahceRedisConnectionFactory;
    @Autowired
    private ChlCouponsService chlCouponsService;
    @Autowired
    private ChlOrderRefundMapper chlOrderRefundMapper;
    @Autowired
    private StoreWithdrawHisMapper storeWithdrawHisMapper;

    public static final String SERIAL_KEY = "SERIAL:NUMBER";
    @Value("${ceres.wx.ma.appid}")
    private String appid;

    @Value("${ceres.wx.ma.secret}")
    private String secret;

    public static RSAAutoCertificateConfig config = null;

//    @Autowired
//    public void setConfig(){
//        config = new RSAAutoCertificateConfig.Builder()
//                .merchantId("1666915143")
//                .privateKeyFromPath("E:\\liliao\\apiclient_key.pem")
//                .merchantSerialNumber("140DEA0F5B3FC9FB0B158EE29CECB62F2307CA74")
//                .apiV3Key("A6fG7K6jL8VwQ5RmP1nZyB4dC3HqT0aS")
//                .build();
//    }

    public static JsapiServiceExtension service = null;

    @Override
    public IPage<ChlOrder> page(IPage page, ChlOrderPageDTO model) {
        return baseMapper.page(page, model);
    }

    /**
     * 后台 假删除订单
     *
     * @param id
     * @return
     */
    @Override
    public int updateChlOrderDelete(Long id) {
        return baseMapper.updateChlOrderDelete(id);
    }

    /**
     * 下单
     *
     * @param placeOrderDTO
     * @return
     */
    @Override
    @Transactional
    public R<ChlPlaceOrderVO> placeOrder(ChlPlaceOrderDTO placeOrderDTO) {
        System.out.println("购买参数:" + placeOrderDTO.toString());
        Member member = memberService.findById(placeOrderDTO.getMid());
        ChlPlaceOrderVO placeOrderVO = new ChlPlaceOrderVO();
        ChlOrder chlOrder = new ChlOrder();
        //余额支付
        if (placeOrderDTO.getPayChannel() == 3) {
            BigDecimal add = new BigDecimal(0);
            if (member.getVipTime() == null || !member.getVipTime().isAfter(LocalDateTime.now())) {
                add = member.getBalance();
            } else {
                add = member.getBalance().add(member.getCoupons());
            }
            if (placeOrderDTO.getCash().compareTo(add) > 0) {
                return R.fail("余额不足");
            }
        }
        /**
         * 下单分为购买消费金和充值vip，店费用
         * 1、如果充值vip 往下走，比如说金钻会员确去充值银钻会员，提示发生错误
         * 2、充值之后，vip到期时间重新计算
         */
        //购买消费金必须是vip身份
        if (placeOrderDTO.getOrderType() == 2) {
            if (member.getVipTime() == null || !member.getVipTime().isAfter(LocalDateTime.now())) {
                return R.fail("您不是vip 不能购买消费金");
            }
        }
        if (placeOrderDTO.getOrderType() == 1) {
            chlOrder.setLoveNum(placeOrderDTO.getLoveNum());
            chlOrder.setPaySum(placeOrderDTO.getCash());
            chlOrder.setLicensePlate(placeOrderDTO.getLicensePlate());
            placeOrderDTO.setNotes("购买VIP");
        } else if (placeOrderDTO.getOrderType() == 2) {
            chlOrder.setPaySum(placeOrderDTO.getCash());
            placeOrderDTO.setNotes("购买消费金");
        } else if (placeOrderDTO.getOrderType() == 3) {
            chlOrder.setLoveNum(placeOrderDTO.getLoveNum());
            chlOrder.setPaySum(placeOrderDTO.getCash().multiply(placeOrderDTO.getLoveNum()));
            placeOrderDTO.setNotes("入住费");
        } else if (placeOrderDTO.getOrderType() == 5) {
            chlOrder.setPaySum(placeOrderDTO.getCash());
            placeOrderDTO.setNotes("充值");
        } else if (placeOrderDTO.getOrderType() == 4) {
            chlOrder.setStoreId(placeOrderDTO.getStoreId());
            chlOrder.setProjectid(placeOrderDTO.getProjectid());
            placeOrderDTO.setNotes("购买服务");
            chlOrder.setPaySum(placeOrderDTO.getCash());
            chlOrder.setCoupons(placeOrderDTO.getCoupons());
        } else if (placeOrderDTO.getOrderType() == 6) {
            placeOrderDTO.setNotes("提现");
            chlOrder.setPaySum(placeOrderDTO.getCash());
        }
        String orderCode = next("", 32);
        chlOrder.setMid(placeOrderDTO.getMid());
        chlOrder.setOrderCode(orderCode);
        chlOrder.setOrderSum(placeOrderDTO.getOrderSum());
        chlOrder.setOrderType(placeOrderDTO.getOrderType());
        chlOrder.setNotes(placeOrderDTO.getNotes());
        chlOrder.setOrderStatus(1);
        chlOrder.setPayChannel(placeOrderDTO.getPayChannel());
        chlOrder.setPhone(member.getPhone());
        chlOrder.setPayTime(LocalDateTime.now());
        baseMapper.insert(chlOrder);
        placeOrderVO.setOrderId(chlOrder.getId());

        //微信app
        if (placeOrderDTO.getPayChannel() == 1) {
//            WxPayAppOrderResult result = wxPay2(orderCode, placeOrderDTO.getCash(), null, placeOrderDTO.getIp(), placeOrderDTO.getNotes());
//            if (result.getPackageValue() != null) {
//                chlOrder.setPrepayId(JSON.toJSONString(result));
//                baseMapper.updateById(chlOrder);
//            } else {
//                chlOrder.setOrderStatus(2);
//                chlOrder.setExamine(1);
//                baseMapper.updateById(chlOrder);
//                return R.fail("下单失败");
//            }
//            placeOrderVO.setObject(result);
            //返回数据，前端调起支付
            PrepayWithRequestPaymentResponse payment = payment(orderCode, member.getOpenid(), placeOrderDTO.getCash().multiply(new BigDecimal(100)));
            placeOrderVO.setObject(payment);
        }//支付宝支付
        else if (placeOrderDTO.getPayChannel() == 2) {
            AlipayTradeAppPayResponse result = aliPay(orderCode, chlOrder.getPaySum(), placeOrderDTO.getNotes());
            if (result.getBody() != null) {
                chlOrder.setPrepayId(JSON.toJSONString(result));
                chlOrder.setExamine(1);
                baseMapper.updateById(chlOrder);
            } else {
                chlOrder.setOrderStatus(2);
                baseMapper.updateById(chlOrder);
                return R.fail("下单失败");
            }
            placeOrderVO.setObject(result);
        }//余额支付
        else if (placeOrderDTO.getPayChannel() == 3 && placeOrderDTO.getOrderType() == 4) {
            if (placeOrderDTO.getCash().compareTo(member.getCoupons()) <= 0) {
                member.setCoupons(member.getCoupons().subtract(placeOrderDTO.getCash()));//使用的消费金支付？
            } else {
                member.setCoupons(new BigDecimal(0));//消费金全部使用
                member.setBalance(member.getBalance().subtract(placeOrderDTO.getCash().subtract(member.getCoupons())));//余额减去不够付的付款金额
            }
            chlOrder.setPayTime(LocalDateTime.now());
            chlOrder.setOrderStatus(3);
            chlOrder.setExamine(1);
            memberService.updateById(member);
            baseMapper.updateById(chlOrder);
            chlOrder.setCodeUrl(qRCodeUrl(chlOrder.getOrderCode()));
            placeOrderVO.setObject(orderCode);
        }
        placeOrderVO.setOrderCode(orderCode);
        return R.success(placeOrderVO);
    }

    //生成二维码图片地址
    public String qRCodeUrl(String content) {
        String fileName = UUID.randomUUID().toString() + StrPool.DOT + "png";
        //日期文件夹
        String relativePath = Paths.get(LocalDate.now().format(DateTimeFormatter.ofPattern(DEFAULT_MONTH_FORMAT_SLASH))).toString();
        // web服务器存放的绝对路径
        String absolutePath = Paths.get(fileProperties.getStoragePath(), relativePath).toString();
        QcodeUtil.getQRCode(content, Paths.get(absolutePath, fileName).toString());
        String url = new StringBuilder(fileProperties.getUriPrefix())
                .append(relativePath)
                .append(StrPool.SLASH)
                .append(fileName)
                .toString();

        //替换掉windows环境的\路径
        url = StrUtil.replace(url, "\\\\", StrPool.SLASH);
        url = StrUtil.replace(url, "\\", StrPool.SLASH);
        return url;
    }

    @Override
    public R<ChlCountinuePayVo> continuePay(ChlContinuePayOrderDTO continuePayOrderDTO) {
        Long mid = continuePayOrderDTO.getMid();
        String orderCode = continuePayOrderDTO.getOrderCode();
        String ip = continuePayOrderDTO.getIp();


        ChlOrder order = baseMapper.selectOne(Wraps.<ChlOrder>lbQ().eq(ChlOrder::getOrderCode, orderCode).eq(ChlOrder::getMid, mid));
        if (order == null) {
            return R.fail("订单不存在");
        }

        Member member = memberService.getById(mid);
        if (member == null) {
            return R.fail("用户信息有误，无法继续付款");
        }
        Object object = null;
        ChlCountinuePayVo countinuePayVo = new ChlCountinuePayVo();


        if (order.getPayChannel() == 1) {
            object = wxPay2(order.getOrderCode(), order.getOrderSum(), member.getOpenid(), ip, order.getNotes());
            if (object == null) {
                return R.fail("继续付款失败");
            }
            order.setPrepayId(JSON.toJSONString(object));
        } else {
            object = aliPay(order.getOrderCode(), order.getOrderSum(), order.getNotes());
            if (object == null) {
                return R.fail("继续付款失败");
            }
            order.setPrepayId(JSON.toJSONString(orderCode));
        }
        countinuePayVo.setObject(object);
        baseMapper.updateById(order);

        return R.success(countinuePayVo);
    }

    /**
     * 店铺核销
     *
     * @return
     */
    @Transactional
    @Override
    public R examine(HeXiaoDto dto) {
        ChlOrder order = baseMapper.findByOrderCodeChlOrder(dto.getOrderCode(), dto.getStoreId());
        if (order == null) {
            return R.fail("订单不存在");
        }
        if (order.getExamine() == 2) {
            return R.fail("订单已核销");
        }

// 暂时不要提成  回头等客户确认
//        Member byId = memberService.getById(order.getMid());
//        if(byId.getReferPhone() != null){
//            Member byOpenid = memberService.findByphone(byId.getPhone());
//            //提成
//            ChlMemberTicheng chlMemberTicheng = new ChlMemberTicheng();
//            chlMemberTicheng.setUserid(order.getMid());
//            chlMemberTicheng.setXiaofei(order.getPaySum());
//            chlMemberTicheng.setHeadimg(byId.getHeadimg());
//            chlMemberTicheng.setNickname(byId.getNickname());
//            chlMemberTicheng.setMid(byOpenid.getId());
//            ChlConfig byparameterUnique = chlConfigMapper.findByparameterUnique("tg.tc");
//            if(byparameterUnique != null){
//                BigDecimal divide = byparameterUnique.getParameterValue().divide(new BigDecimal(100));
//                chlMemberTicheng.setTicheng(order.getPaySum().multiply(divide));
//            }
//            chlMemberTichengMapper.insert(chlMemberTicheng);
//            //余额加上提成
//            byOpenid.setBalance(byOpenid.getBalance().add(chlMemberTicheng.getTicheng()));
//            memberService.updateById(byOpenid);
//        }
        order.setExamine(2);
        order.setShiyongTime(LocalDateTime.now());
        baseMapper.updateById(order);
        /**
         * 核销成功  修改店铺营业额
         */
        Store store = storeService.getById(order.getStoreId());
        store.setOrderQuantity(store.getOrderQuantity() + 1);
        store.setTurnover(store.getTurnover().add(order.getPaySum()));
        storeService.updateAllById(store);
        return R.success();
    }

    /**
     * 申请退款
     *
     * @return
     */
    @Transactional
    @Override
    public R refund(ChlOrderRefund refund) {

        ChlOrder order = baseMapper.selectOne(Wraps.<ChlOrder>lbQ().eq(ChlOrder::getOrderCode, refund.getOrderCode()));
        Member byId = memberService.findById(refund.getMid());
        if (order == null) {
            return R.fail("订单不存在");
        }
        if (order.getExamine() == 2) {
            return R.fail("已核销不能退款");
        }
        if (order.getOrderStatus() != 3) {
            return R.fail("订单错误");
        }
        try {
            //余额支付
            if (order.getPayChannel() == 3) {
                byId.setBalance(byId.getBalance().add(order.getPaySum()));
            } else if (order.getPayChannel() == 1) {
                //微信
                WxPayRefundRequest req = new WxPayRefundRequest();
                //本次退款的退款单号
                req.setOutRefundNo(System.currentTimeMillis() + "");
                //支付的时候传入的商家的支付订单编号
                req.setOutTradeNo(order.getOrderCode());
                //订单总金额为支付的金额
                req.setTotalFee(order.getPaySum().intValue());
                //只退订单的金额，不退运费
                req.setRefundFee(order.getPaySum().intValue());
                payService.refund(req);
            }
            if (order.getPayChannel() == 2) {
                //支付宝
                AlipayTradeRefundApplyModel applyModel = new AlipayTradeRefundApplyModel();
                applyModel.setOutTradeNo(order.getOrderCode());
                applyModel.setOutRequestNo(System.currentTimeMillis() + "");
                applyModel.setRefundAmount(order.getPaySum().toString());
                //退款描述
                applyModel.setRefundReason("服务退款");
                AlipayTradeRefundResponse refund2 = payService.refund(applyModel);
            }
        } catch (Exception e) {
            log.error("refund fail:" + e.getMessage(), e);
            return R.fail("申请退款失败");
        }
        //退回消费金
        byId.setCoupons(byId.getCoupons().add(order.getCoupons()));
        memberService.updateById(byId);
        order.setNotes("退款");
        order.setOrderStatus(4);
        order.setTuiTime(LocalDateTime.now());
        baseMapper.updateById(order);
        chlOrderRefundMapper.insert(refund);
        return R.success();
    }

    /**
     * 我的订单
     *
     * @param mid
     * @return
     */
    @Override
    public R myOeder(Long mid) {
        List<MyOederVo> myOederVos = baseMapper.myOeder(mid);
        for (MyOederVo myOederVo : myOederVos) {
            if (commentMapper.findByChlorderId(myOederVo.getId(), mid) != null) {
                myOederVo.setB(true);
            }
        }
        return R.success(myOederVos);
    }

    @Override
    public R wxSelectOrder(String id) {
        ChlOrder byId = baseMapper.selectById(id);
        try {
            //私钥文件路径（本地自己测试看自己的私钥文件存放路径）
//            String filePath ="E:\\liliao\\apiclient_key.pem";
            String filePath = "/opt/llc/cert/apiclient_key.pem";
            // 一个商户号只能初始化一个配置，否则会因为重复的下载任务报错
            if (config == null) {
//                setConfig();
                config = new RSAAutoCertificateConfig.Builder()
                        .merchantId("1666915143")
                        .privateKeyFromPath(filePath)
                        .merchantSerialNumber("140DEA0F5B3FC9FB0B158EE29CECB62F2307CA74")
                        .apiV3Key("A6fG7K6jL8VwQ5RmP1nZyB4dC3HqT0aS")
                        .build();
            }
            // 构建service
            if (service == null) {
                service = new JsapiServiceExtension.Builder().config(config).build();
            }
            QueryOrderByOutTradeNoRequest queryOrderByOutTradeNoRequest = new QueryOrderByOutTradeNoRequest();
            queryOrderByOutTradeNoRequest.setMchid("1666915143");
            queryOrderByOutTradeNoRequest.setOutTradeNo(byId.getOrderCode());
            Transaction transaction = service.queryOrderByOutTradeNo(queryOrderByOutTradeNoRequest);
            String string = transaction.getTradeState().toString();
            if (string.equals("")) {
//                payCallBackService.updateOrderAndUser(byId);
            } else {

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 删除我的订单
     *
     * @param id
     * @return
     */
    @Override
    public R deleteOeder(Long id) {
        return R.success(baseMapper.deleteById(id));
    }

    /**
     * 订单消费金额
     *
     * @return
     */
    @Override
    public R xiadan(XiadanDto dto) {
        XiadanVo vo = new XiadanVo();
        ChlConfig chlConfig = chlConfigMapper.findByparameterUnique("yhj.jm");
        BigDecimal subtract = new BigDecimal(0);
        if (chlConfig != null) {
            subtract = chlConfig.getParameterValue().multiply(dto.getPrice()).divide(new BigDecimal(100));
        }
        Member byId = memberService.getById(dto.getUserId());
        if (byId.getCoupons().compareTo(subtract) > 0) {
            vo.setYouhui(subtract);
            vo.setYouhuihou(dto.getPrice().subtract(subtract));
        } else {
            BigDecimal subtract1 = subtract.subtract(byId.getCoupons());
            vo.setYouhui(subtract.subtract(subtract1));
            vo.setYouhuihou(dto.getPrice().subtract(vo.getYouhui()));
        }
        vo.setYouhuihou(vo.getYouhuihou().setScale(2, BigDecimal.ROUND_HALF_UP));
        vo.setYouhui(vo.getYouhui().setScale(2, BigDecimal.ROUND_HALF_UP));
        return R.success(vo);
    }

    @Override
    public R getOeder(Long id) {

        return R.success(baseMapper.getOeder(id));
    }

    /**
     * 我的钱包
     *
     * @return
     */
    @Override
    public R myqianbao(MyqianbaoDto dto) {
        MyqianbaoVo vo = new MyqianbaoVo();
        List<MyqianbaodetailsVo> list = new ArrayList<>();
        Member byId = memberService.getById(dto.getMid());
        vo.setBalance(byId.getBalance());
        //总资产=余额+消费金
        vo.setZongzichan(byId.getBalance().add(byId.getCoupons()));
        LocalDateTime localDateTime = LocalDateTime.now();
        String format = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        vo.setJinreshouyi(chlMemberTichengMapper.Jinreshouyi(format, dto.getMid()));
        vo.setLeijishouyi(chlMemberTichengMapper.Leijishouyi(dto.getMid()));
        List<ChlOrder> byMid = baseMapper.myqianbao(dto.getMid(), dto.getType());
        for (ChlOrder chlOrder : byMid) {
            if (chlOrder.getNotes().equals("购买服务")) {
                MyqianbaodetailsVo myqianbaodetailsVo = baseMapper.storeName(chlOrder.getId());
                myqianbaodetailsVo.setNotes(myqianbaodetailsVo.getStoreName() + "-" + myqianbaodetailsVo.getTitle());
                list.add(myqianbaodetailsVo);
            } else {
                list.add(baseMapper.findByid(chlOrder.getId()));
            }
        }
        vo.setList(list);
        return R.success(vo);
    }

    @Override
    public List<ChlLbt> applist() {
        System.out.println(chlLbtMapper.lbt());
        return chlLbtMapper.lbt();
    }

    @Override
    public List<Vedio> selectVideo() {
        return chlLbtMapper.video();
    }

    @Override
    @Transactional
    public R withdraw(StoreWithdrawHisSaveDTO dto) {
        Store store = storeService.fidMid(dto.getMid());
        if (store == null) {
            return R.fail("没有店铺");
        }
        //现金提现
        if (dto.getCash().compareTo(store.getTurnover()) == 1) {
            return R.fail("提现金额不足");
        } else {
            ChlOrder chlOrder = new ChlOrder();
            chlOrder.setNotes("提现");
            chlOrder.setOrderSum(dto.getCash());
            chlOrder.setPaySum(dto.getCash());
            chlOrder.setPayTime(LocalDateTime.now());
            String orderCode = next("", 32);
            chlOrder.setOrderCode(orderCode);
            chlOrder.setOrderStatus(5);
            chlOrder.setPayChannel(dto.getAccountType());
            chlOrder.setMid(dto.getMid());
            chlOrder.setOrderType(7);
            baseMapper.insert(chlOrder);
            dto.setSupplyStatus(AdjustStatuseEnum.JXZ_STATUS.getCode());
            StoreWithdrawHis result = new StoreWithdrawHis();
            BeanUtils.copyProperties(dto, result);
            result.setWithdrawId(chlOrder.getId().toString());
            storeWithdrawHisMapper.insert(result);

        }
        return R.success();
    }

    /**
     * 店铺提现账单查询
     *
     * @return
     */
    @Override
    public R storeTxBill(StoreBillDto dto) {
        return R.success(baseMapper.storeTxBill(dto));
    }

    /**
     * 店铺账单查询
     *
     * @param dto
     * @return
     */
    @Override
    public R storeBill(StoreBillDto dto) {
        return R.success(baseMapper.storeBill(dto));
    }


    private AlipayTradeAppPayResponse aliPay(String outTradeNo, BigDecimal sum, String orderInfo) {
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setOutTradeNo(outTradeNo);
        model.setTotalAmount(String.valueOf(sum));
        model.setSubject(orderInfo);
        model.setBody(orderInfo);
        model.setTimeoutExpress("30m");
        model.setProductCode("FAST_INSTANT_TRADE_PAY");
        return payService.unifiedOrder(model);
    }

    /**
     * 手机支付H5
     */
    private AlipayTradeWapPayResponse aliPay2(String outTradeNo, BigDecimal sum, String orderInfo) {
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
        //传入quit_url
        // model.setQuitUrl("< a href=”javascript:history.back(-1)”>返回上一页</ a>");
        model.setOutTradeNo(outTradeNo);
        model.setTotalAmount(String.valueOf(sum));
        model.setSubject(orderInfo);
        model.setBody(orderInfo);
        model.setTimeoutExpress("30m");
        model.setProductCode("QUICK_WAP_PAY");
        return payService.unifiedOrder(model);
    }

    private WxPayAppOrderResult wxPay2(String outTradeNo, BigDecimal sum, String openId, String ip, String orderInfo) {
        WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();

        //商户订单号
        request.setOutTradeNo(outTradeNo);
        //微信用户ID
        request.setOpenid(openId);
        //内容
        request.setBody(outTradeNo);
        //总金额  单位：分
        request.setTotalFee(sum.multiply(new BigDecimal(100)).intValue());
        //终端IP
        request.setSpbillCreateIp(ip);
        request.setTradeType(WxPayConstants.TradeType.JSAPI);
        request.setAppid(appid);
        request.setNonceStr(secret);
        //埋点支付
        return payService.unifiedOrder(request);
    }

    public String next(String prefix, int len) {
        if (len < 15) {
            throw new BizException("入参错误");
        }
        RedisAtomicLong redisAtomicLong = new RedisAtomicLong(SERIAL_KEY,
                j2CahceRedisConnectionFactory);
        String dateStr = LocalDateTime.now()
                .format(DateTimeFormatter.ofPattern(DatePattern.PURE_DATETIME_PATTERN));
        len = len - dateStr.length();
        redisAtomicLong.expire(60, TimeUnit.SECONDS);
        String serial = String.valueOf(redisAtomicLong.incrementAndGet());
        if (serial.length() > len) {
            redisAtomicLong = new RedisAtomicLong(SERIAL_KEY, j2CahceRedisConnectionFactory, 1);
            serial = String.valueOf(redisAtomicLong.incrementAndGet());
        }
        return prefix + dateStr + StrUtil.fillBefore(serial, '0', len);
    }

    public PrepayWithRequestPaymentResponse payment(String orderCode, String openId, BigDecimal cash) {
        // 订单号
        String orderUuid = orderCode;
        //元转换为分
        Integer amountInteger = cash.intValue() * 100;
        //私钥文件路径（本地自己测试看自己的私钥文件存放路径）
//        String filePath ="E:\\liliao\\apiclient_key.pem";
        String filePath = "/opt/llc/cert/apiclient_key.pem";
        // 一个商户号只能初始化一个配置，否则会因为重复的下载任务报错
        if (config == null) {
            config = new RSAAutoCertificateConfig.Builder()
                    .merchantId("1666915143")
                    .privateKeyFromPath(filePath)
                    .merchantSerialNumber("140DEA0F5B3FC9FB0B158EE29CECB62F2307CA74")
                    .apiV3Key("A6fG7K6jL8VwQ5RmP1nZyB4dC3HqT0aS")
                    .build();
        }
        // 构建service
        if (service == null) {
            service = new JsapiServiceExtension.Builder().config(config).build();
        }
        //组装预约支付的实体
        PrepayRequest request = new PrepayRequest();
        //计算金额
        Amount amount = new Amount();
        amount.setTotal(cash.intValue());
        amount.setCurrency("CNY");
        request.setAmount(amount);
        String appid = "wx31883f01947e7804";
        //公众号appId
        request.setAmount(amount);
        request.setAppid(appid);
//        request.setAmount(new PrepayRequest().getAmount());
//        request.getAmount().setTotal(1);
        request.setAmount(amount);

        //商户号
        request.setMchid("1666915143");
        //支付者信息
        Payer payer = new Payer();
        payer.setOpenid(openId);
        request.setPayer(payer);
        //描述
        request.setDescription("小程序支付");
        //微信回调地址，需要是https://开头的，必须外网可以正常访问
        request.setNotifyUrl("https://sanshitang1863.com/api/pay/notify/order");
        //订单号
        request.setOutTradeNo(orderUuid);

        // 加密
        PrepayWithRequestPaymentResponse payment = service.prepayWithRequestPayment(request);
        //默认加密类型为RSA
        payment.setSignType("MD5");
        System.out.println(payment);
        return payment;
    }
}
